package com.smap.control;

import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.smap.common.Callback;
import com.smap.common.GeoAPI;
import com.smap.core.Layer;
import com.smap.core.Map;
import com.smap.core.XY;
import com.smap.event.MapEvent;

public class NavigateControl extends AbstractControl {

	int[] rect = null;

	public void onEvent(MapEvent evt) {
		if ("draging".equals(evt.type)) {
			if (evt.btn == 1) {

				if ((evt.offsetX > 0) && (evt.offsetY > 0)) {

					Context2d ctx = map.getScreen();
					if (rect != null) {
						ctx.clearRect(rect[0] - 1, rect[1] - 1, rect[2] + 2,
								rect[3] + 2);
					} else {
						rect = new int[4];
					}
					rect[0] = MapEvent.START_X;
					rect[1] = MapEvent.START_Y;
					rect[2] = evt.offsetX;
					rect[3] = evt.offsetY;
					ctx.setStrokeStyle("blue");
					ctx.setGlobalAlpha(1);
					ctx.setLineWidth(2);
					ctx.strokeRect(rect[0], rect[1], rect[2], rect[3]);
				}
			} else {
				map.setScreenOffset(evt.offsetX, evt.offsetY);
				map.setCursor("move");
			}
		} else if ("dragend".equals(evt.type)) {
			if (rect != null) {
				Context2d ctx = map.getScreen();
				ctx.clearRect(rect[0] - 1, rect[1] - 1, rect[2] + 2,
						rect[3] + 2);
				rect[0] = rect[0] - map.getWidth() / 2;
				rect[1] = rect[1] - map.getHeight() / 2;
				map.zoomTo(rect);
				rect = null;
			} else {
				map.updateLocation();
			}
			map.setCursor(null);
		} else if ("mousewheel".equals(evt.type)) {
			if (evt.deltaY > 0) {
				map.zoomOut();
			} else {
				map.zoomIn();
			}
		} else if ("dbclick".equals(evt.type)) {
			XY newCentre = map.pixelToMap(new XY(evt.x, evt.y));
			map.zoom(newCentre, 15);
		}
	}

	public void onResize() {

	}

	public void command(String cmd) {
		if ("zoomIn".equals(cmd)) {
			map.zoomIn();
		} else if ("zoomOut".equals(cmd)) {
			map.zoomOut();
		} else if ("currenLocation".equals(cmd)) {
			GeoAPI geo = new GeoAPI(new Callback() {
				public void exe(Object... obj) {
					Double lon = (Double) obj[0];
					Double lat = (Double) obj[1];
					map.zoomByLonLat(lon, lat, null);
				}
			});
			geo.getLoc();
		} else if ("switchBaseLayer".equals(cmd)) {
			Layer layer = map.getLayers().get(0);
			layer.setType(null);
			map.draw(false);
		}
	}

	@Override
	public void install(Map map) {
		super.install(map);
		toolBar.addBtn("zoomIn", "+", false);
		toolBar.addBtn("zoomOut", "-", false);
		toolBar.addBtn("currenLocation", "*", false);
		toolBar.addBtn("switchBaseLayer", "^", false);
	}
}
